package com.home_school_platform.controller;

import com.home_school_platform.service.WeChatSubscriptionService;
import com.home_school_platform.service.impl.WeChatSubscriptionServiceImpl;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * 微信公众号Controller
 * @author 卓汉杰
 * */

@CrossOrigin
@Controller
@Api("微信公众号接口")
public class WeChatSubscriptionConterller {

//    @Autowired
//    private StringRedisTemplate stringRedisTemplate;  //对字符串支持比较友好,不能存储对象
//    @Autowired
//    private RedisTemplate redisTemplate;  //存储对象

    /**
     * 微信公众号业务逻辑接口
     * */
    @Autowired
    WeChatSubscriptionServiceImpl weChatSubscriptionService;

    /**
     * 微信接口接入测试
     * @param signature 	微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
     * @param timestamp 	时间戳
     * @param nonce 	随机数
     * @param echostr 	随机字符串
     * */
    @GetMapping("/wechatInterface")
    @ResponseBody
    public String wechatInterfaceTest(String signature,String timestamp ,String nonce ,String echostr){
        //校验证签名

        if(weChatSubscriptionService.check(signature,timestamp,nonce)) {
            System.out.println("接入成功");
            //若确认此次GET请求来自微信服务器，请原样返回echostr参数内容
            return echostr;

        }else {
            System.out.println("接入失败");
            return null;
        }

    }


    /**
     * 微信公众号接收用户消息
     * 当普通微信用户向公众账号发消息时，微信服务器将POST消息的XML数据包到开发者填写的URL上。
     * 参考文档 https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Receiving_standard_messages.html
     * */
    @PostMapping("/wechatInterface")
    @ResponseBody
    public String wechatGetMessage(HttpServletRequest request) throws IOException {


        request.setCharacterEncoding("utf8");

        //处理消息和事件推送
        Map<String, String> requestMap = weChatSubscriptionService.parseRequest(request.getInputStream());
        System.out.println(requestMap);
        //准备回复的数据包
        String respXml = weChatSubscriptionService.getRespose(requestMap);
        System.out.println(respXml);

        return respXml;
    }



}
